package com.lovezy.platform.interceptor;

import com.lovezy.platform.common.extend.ExtendService;
import com.lovezy.platform.common.prop.Constant;
import com.lovezy.platform.core.base.SiteContext;
import com.lovezy.platform.core.jwt.JwtUtil;
import com.lovezy.platform.core.spring.SpringContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import static com.lovezy.platform.core.exception.DefaultErrorCode.NOT_LOGIN;
import static com.lovezy.platform.core.utils.ObjectUtil.nonNull;

/**
 * Token拦截器
 * Created by jin on 2017/11/14.
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String authorization = httpServletRequest.getHeader("Authorization");
        if (authorization != null) {
            Map<String, Object> claims = JwtUtil.parserJavaWebToken(authorization);
            if (claims != null) {
                TokenValidResult tokenValidResult = checkValid(claims);
                if (tokenValidResult.isSuccess()) {
                    SiteContext.setCurrentMid(tokenValidResult.getMid());
                }
            }
        }

        return true;
    }

    protected TokenValidResult checkValid(Map<String, Object> claims) {
        String mid = (String) claims.get("mid");
        String tokenId = (String) claims.get("token");
        Long timestamp = (Long) claims.get("time");
        nonNull("用户Token校验错误", mid, tokenId, timestamp);
        Date time = new Date(timestamp);

        ExtendService extendService = SpringContext.getContext().getBean(ExtendService.class);
        Boolean right = extendService.validToken(mid, tokenId);
        if (!right) {
            return new TokenValidResult( NOT_LOGIN, "登陆信息校验错误");
        }

        Date now = new Date();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.DAY_OF_YEAR, Constant.TOKEN_VALID_TIME);
        if (calendar.getTime().before(now)) {
            return new TokenValidResult(NOT_LOGIN, "登陆已过期");
        }

        return new TokenValidResult(mid);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        SiteContext.clearCurrentMid();
    }
}
